//
//  NoticeViewController.m
//  iBaby365v2
//
//  Created by Kirinrin on 14-6-28.
//  Copyright (c) 2014年 suplus. All rights reserved.
//

#import "NoticeViewController.h"
#import "UIAlertView+Kirinrin.h"
#import "MJRefresh.h"
#import "UIImageView+AFNetworking.h"
#import "NoticeDetailViewController.h"
#import "NetworkAccessManager.h"

#define kMaxReturnCount     10
#define kViewDetailSegueId  @"toViewDetail"

@interface NoticeViewController ()<MJRefreshBaseViewDelegate>
@property (weak, nonatomic) IBOutlet UILabel *content;
@property (weak, nonatomic) IBOutlet UIImageView *photoView;
@property (weak, nonatomic) IBOutlet UILabel *summary;


@property(strong, nonatomic)NSMutableArray *tableData;

@property (nonatomic, weak) MJRefreshFooterView *footerNotice;
@property (nonatomic, weak) MJRefreshHeaderView *headerNotice;

@end
static NSUInteger currentCount;
@implementation NoticeViewController{
    
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
 
    if (self.appDelegate.userType == UserTypeParent) {
        self.navigationItem.rightBarButtonItem = nil;
    }
    MJRefreshHeaderView *header = [MJRefreshHeaderView header];
    header.scrollView = self.tableView;
    header.delegate = self;
    [header beginRefreshing];
    self.headerNotice = header;
    
    MJRefreshFooterView *footer = [MJRefreshFooterView footer];
    footer.scrollView = self.tableView;
    footer.delegate = self;
    self.footerNotice = footer;
    currentCount = 0;
    
//    __block NoticeViewController *weakSelf = self;
//    [self.tableView addHeaderWithCallback:^{
//        [weakSelf loadRemoteData:0 maxCount:kMaxReturnCount];
//    }];
//
//    [self.tableView addFooterWithCallback:^{
//        [weakSelf loadRemoteData:currentCount maxCount:kMaxReturnCount ];
//    }];
    
//    [self loadRemoteData:0 maxCount:kMaxReturnCount];
}

-(void)dealloc
{
    [self.headerNotice free];
    [self.footerNotice free];
}

-(void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView
{
    
    __block NoticeViewController *weakSelf = self;
    if ([refreshView isKindOfClass:[MJRefreshHeaderView class]]) {
        [weakSelf loadRemoteData:0 maxCount:kMaxReturnCount];
    }else{
        [weakSelf loadRemoteData:currentCount maxCount:kMaxReturnCount ];
    }
}
-(void)viewWillAppear:(BOOL)animated{
//    [self loadRemoteData:0 maxCount:kMaxReturnCount];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)loadRemoteData:(NSUInteger)firstRecturnCoun maxCount:(NSUInteger)maxReturnCount{
    NSString *uriString = [NSString stringWithFormat:@"Notice.json"];
    NSDictionary *parameters = @{@"key": self.appDelegate.accessKey, @"kClassId":self.appDelegate.user[@"kClassId"], @"maxReturnCount":@(maxReturnCount), @"firstReturnCount":@(firstRecturnCoun)};
    
    [[NetworkAccessManager shareManager]GET:uriString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"opernation: %@\nresponse: %@", operation, responseObject);
        
        int resultCode = [responseObject[@"result"]intValue];
        if (resultCode == 0) {
            
            if (firstRecturnCoun == 0) {
                [self.tableData removeAllObjects];
//                [self.tableView headerEndRefreshing];
//                [self.headerNotice endRefreshing];
            }else{
//                [self.tableView footerEndRefreshing];
//                [self.footerNotice endRefreshing];
            }
            
            [self.tableData addObjectsFromArray:responseObject[@"data"]];
            currentCount = self.tableData.count;
            [self.tableView reloadData];
        }else{
            [UIAlertView alertWithRemoteError:resultCode];
        }
        if (firstRecturnCoun == 0) {
            //            [self.tableView headerEndRefreshing];
            [self.headerNotice endRefreshing];
        }else{
            //            [self.tableView footerEndRefreshing];
            [self.footerNotice endRefreshing];
        }

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [UIAlertView alertWithNetworkError];
        NSLog(@"opernation: %@\nerror: %@", operation, error);
        if (firstRecturnCoun == 0) {
//            [self.tableView headerEndRefreshing];
            [self.headerNotice endRefreshing];
        }else{
//            [self.tableView footerEndRefreshing];
            [self.footerNotice endRefreshing];
        }
        [UIAlertView alertWithNetworkError];
    }];
}

#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:kViewDetailSegueId]) {
        NSIndexPath *indexPath = sender;
        NSDictionary *data = self.tableData[indexPath.row];
        NoticeDetailViewController *controller = segue.destinationViewController;
        controller.contentString = data[@"content"];
        if (data[@"title"] != [NSNull null]) {
            controller.titleTextString = data[@"title"];
        }else{
            controller.titleTextString = @"通知";
        }
        
    }
}


#pragma mark - UITableViewDelegate & UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [_tableData count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView  dequeueReusableCellWithIdentifier:@"cell"];
    UILabel *content = (UILabel *)[cell.contentView viewWithTag:100];
    UIImageView *photo = (UIImageView *)[cell.contentView viewWithTag:101];
    UILabel *summary = (UILabel *)[cell.contentView viewWithTag:102];
    UILabel *title = (UILabel *)[cell.contentView viewWithTag:103];
    
    NSDictionary *data = _tableData[indexPath.row];
    content.text = data[@"content"];
    if (data[@"title"] != [NSNull null]) {
        title.text =data[@"title"];
    }
    if (![data[@"photoPre"] isEqual:[NSNull null]]) {
        [photo setImageWithURL:[NSURL URLWithString:data[@"photoPre"]]placeholderImage:nil];
    }
    NSString *summaryString = [NSString stringWithFormat:@"%@老师 %@",data[@"senderName"], data[@"dateTime"]];
    summary.text = summaryString;
    
    return cell;
}


-(BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}

#pragma mark - getter & setter
-(NSMutableArray *)tableData{
    if (!_tableData) {
        _tableData = [[NSMutableArray alloc]init];
    }
    return _tableData;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self performSegueWithIdentifier:kViewDetailSegueId sender:indexPath];
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}
@end
